package org.theSeed.controller;

import cn.hutool.core.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.theSeed.base.exp.BuzExp;
import org.theSeed.base.pojo.sysEnum.SysCode;
import org.theSeed.base.pojo.vo.R;
import org.theSeed.pojo.dto.UserInfoUserDetails;
import org.theSeed.rbacSecurityJwt.utils.LoginUtil;
import org.theSeed.utils.LoginHelper;

import java.util.Map;

/**
 * 登录控制器
 */
@RestController
@RequestMapping
public class LoginController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 登录
     * @param body
     * @return
     */
    @GetMapping("login")
    public R login2(@RequestParam Map<String,String> body){
        String username = body.get("username");
        String password = body.get("password");

        UserInfoUserDetails userDetails = (UserInfoUserDetails)(userDetailsService.loadUserByUsername(username));
        if (ObjectUtil.isNull(userDetails)){
            throw new BuzExp(SysCode.UN_AUTH,"用户不存在");
        }
        if (passwordEncoder.matches(password,userDetails.getPassword())){
            return R.success(LoginUtil.login(userDetails));
        }else{
            return R.success("密码错误");
        }
    }

    /**
     * 获取用户登录信息
     * @return
     */
    @GetMapping("getUserInfo")
    public R getUserInfo(){
        return R.success(LoginHelper.getLoginInfo());
    }

    /**
     * 鉴权测试1
     * @return
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping("test1")
    public R getUserInfo1(){
        return R.success(LoginHelper.getLoginInfo());
    }

    /**
     * 鉴权测试2
     * @return
     */
    @PreAuthorize("hasRole('admin1')")
    @GetMapping("test2")
    public R getUserInfo2(){
        return R.success(LoginHelper.getLoginInfo());
    }

    /**
     * 鉴权测试3
     * @return
     */
    @PreAuthorize("hasAuthority('demo:test')")
    @GetMapping("test3")
    public R getUserInfo3(){
        return R.success(LoginHelper.getLoginInfo());
    }
}
